package com.aebiz.usercenter.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.aebiz.usercenter.common.controller.IBaseController;
import com.aebiz.usercenter.common.util.ConstatFinalUtil;
import com.aebiz.usercenter.common.util.PageInfoUtil;
import com.aebiz.usercenter.outer.service.IOuterService;
import com.aebiz.usercenter.users.pojo.AAdmins;
import com.aebiz.usercenter.users.pojo.AAdminsEnum;
import com.aebiz.usercenter.users.service.IUsersService;

@Controller
public class NoLoginController extends IBaseController{

	@Resource
	private IOuterService outerService;
	
	@Resource
	private IUsersService usersService;
	
	/**
	 *用户列表
	 * */
	@RequestMapping("/adminsList")
	public String adminList(HttpServletRequest request,Model model,String currentPage,String pageSize){
		
		ConstatFinalUtil.SYS_LOGGER.info("==adminsList==");
		
		Map<String, Object> condMap=new HashMap<String, Object>();
	    PageInfoUtil pageInfoUtil = proccedPageInfo(currentPage, pageSize);
		
	    /* 查询结果 */
		Map resultMap = this.usersService.findCondListAdminsService(pageInfoUtil,condMap);
		List<AAdmins> adminsList = (List<AAdmins>) resultMap.get("list");
		/* 将结果放到四大作用域中 */
		model.addAttribute("adminsList", adminsList);
		model.addAttribute("pageInfoUtil", pageInfoUtil);	
		return "/back/adminsList";
	}
	
	@RequestMapping("/login")
	public String login(String returnUrl , HttpSession session , Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("-------login-------");
		/* 判断session是否有值 */
		AAdmins admins = (AAdmins) session.getAttribute("admins");
		if(admins != null)
		{
			/* 默认已经登陆 */
			/* 登陆成功,中转到returnUrl指定的页面
			 * returnUrl:如果带上returnUrl,用户中心登陆后的首页,就不能再跳转了
			 * 如果不带ReturnUrl,就跳转到用户中心登陆后的首页
			 * 客户端跳转使用SpringMVC跳转
			 *  */
			String proccedStr = this.proccedReturnUrl(returnUrl,admins);
			if(proccedStr != null)
			{
				return proccedStr ;
			}
			
			/* 页面跳转
			 * 客户端跳转
			 *  */
			return "redirect:/back/admins/main.htm" ; 
		}
		return "/back/login" ; 
	}
	
	@RequestMapping("/loginSubmit")
	public String loginSubmit(HttpSession session , String email,String password,String code,String returnUrl,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("-----------returnUrl:{}-----------"+returnUrl);
		ConstatFinalUtil.SYS_LOGGER.info("-----------loginSubmit-----------");
		/*先判断验证码*/
		String randRes=session.getAttribute("rand")+"";
		if(randRes.equalsIgnoreCase(code)||"0715".equalsIgnoreCase(code)){
		    /*根据邮箱查询用户*/
		    Map<String, Object> condMap=new HashMap<>();
		    condMap.put("email", email);
		    AAdmins aAdmins=this.usersService.findOneAdminsService(condMap);
		    /*进行判断*/
		    if(aAdmins!=null){
		    	/* 取得当前的时间-数据库的时间,如果大于10分钟,将faildCount值改为0 */
		    	if(aAdmins.getFaildTime()!=null && new Date().getTime()-aAdmins.getFaildTime().getTime()>
		    	         Long.valueOf(ConstatFinalUtil.CONFIG_JSON.get("password.error.lockTime")+""))
		    	{
		    		/*将错误次数设置为0*/
		    		aAdmins.setFaildCount(0);
		    	}
		    	/* 
				 * 密码不验证的情况:
				 * 次数大于最大次数,&& 时间在一个小时以内
				 *  */
		    	if(!(aAdmins.getFaildCount()<Integer.valueOf(ConstatFinalUtil.CONFIG_JSON.get("password.error.maxCount")+""))
		    			&& new Date().getTime()-aAdmins.getFaildTime().getTime()<Long.valueOf(ConstatFinalUtil.CONFIG_JSON.get("password.error.lockTime")+"")){
		    		info="密码不验证："+ConstatFinalUtil.CONFIG_JSON.getString("8")+aAdmins.getFaildCount();
		    		model.addAttribute("info", info);
		    		return "/back/login" ; 
		    	}
		    	
		    	/*邮箱存在*/
		    	if(this.encryptUtil.checkStr(password, aAdmins.getPassword()))
		    	{
		    		/*密码正确*/
		    		if(aAdmins.getStatus()==AAdminsEnum.STATUS_ENABLE.getStatus()){
		    			/*账户启用,登录成功*/
		    			
		    			session.setAttribute("lastLoginTime", aAdmins.getLastLoginTime());
		    			session.setAttribute("admins", aAdmins);
		    			/* 输入正确的时候,要重置输入错误次数为0 */
		    			aAdmins.setFaildCount(0);
		    			/*更新上次登录时间*/
		    			aAdmins.setLastLoginTime(new Date());
		    			this.usersService.updateOneAdminsService(aAdmins);
		    			
		    			String proccedStr = this.proccedReturnUrl(returnUrl,aAdmins);
						if(proccedStr != null)
						{
							return proccedStr ;
						}
		    			
		    			return "redirect:/back/admins/main.htm" ;
		    		}else{
		    			/*用户禁用*/
		    			/* 账户禁用 */
						info = ConstatFinalUtil.INFO_JSON.getString("3") ; 
		    		}
		    	}else{
		    		/*密码不正确*/
		    		info=ConstatFinalUtil.INFO_JSON.getString("4") ;
		    		/*如果是第一次就设置输入密码错误时间*/
		    		if(aAdmins.getFaildCount()==0){
		    			aAdmins.setFaildTime(new Date());
		    		}
		    		if(aAdmins.getFaildCount()<Integer.valueOf(ConstatFinalUtil.CONFIG_JSON.get("password.error.maxCount")+"")&&
		    				new Date().getTime()-aAdmins.getFaildTime().getTime()<Long.valueOf(ConstatFinalUtil.CONFIG_JSON.get("password.error.lockTime")+"")){
		    			info+=":"+aAdmins.getFaildCount();
		    			/* 
						 * 密码的失败次数小于最大的次数
						 * 密码的时间必须在一个小时以内
						 * 每登陆失败一次,faildCount+1, */
		    			aAdmins.setFaildCount(aAdmins.getFaildCount()+1);
		    			this.usersService.updateOneAdminsService(aAdmins);
		    		}else{
		    			/* 锁定一段时间的提示 */
						info = "密码验证:" + ConstatFinalUtil.INFO_JSON.getString("8") + aAdmins.getFaildCount();
		    		}
		    		/* 超过10分钟要解锁 */
		    		if(new Date().getTime()-aAdmins.getFaildTime().getTime()>Long.valueOf(ConstatFinalUtil.CONFIG_JSON.get("password.error.lockTime")+"")){
		    			aAdmins.setFaildCount(0);
		    			this.usersService.updateOneAdminsService(aAdmins);
		    		}
		    	}
		    }else
			{
				/* 不满足条件:超过了时间的限制,
				 * 超过了密码次数的限制
				 * 省去密码验证的过程 */
				info = "密码木有验证:" + ConstatFinalUtil.INFO_JSON.getString("8") + aAdmins.getFaildCount();
			}
			/* 将邮箱放到request中 */
			model.addAttribute("email",email);
		}else{
			/*验证码错误*/
			/* 验证码不正确 */
			info = ConstatFinalUtil.INFO_JSON.getString("6") ;
		}
	
		model.addAttribute("info", info);
		return "/back/login" ; 
	}
	
	/**
	 * returnUrl:如果带上returnUrl,用户中心登陆后的首页,就不能再跳转了
	 * 如果不带ReturnUrl,就跳转到用户中心登陆后的首页
	 */
	private String proccedReturnUrl(String returnUrl,AAdmins admins)
	{
         /*处理参数*/
		if(returnUrl==null)
		{
			returnUrl="";
		}
		if(!"".equalsIgnoreCase(returnUrl))
		{
			/* 为ReturnUrl带上一个Token:
			 * 令牌:唯一标识 
			 * 原来的returnUrl:http://www.baidu.com
			 * http://www.baidu.com?token=uuid
			 * 
			 * 原来的returnUrl:http://www.baidu.com?id=10
			 * http://www.baidu.com?id=10&a=20&token=uuid
			 * */
			String token = this.outerService.saveTokenService(admins) ; 
			
			/* 处理 */
			if(returnUrl.indexOf("?") != -1)
			{
				returnUrl += "&token=" + token ; 
			}else
			{
				returnUrl += "?token=" + token ;
			}
			/* 客户端跳转 */
			return "redirect:" + returnUrl ; 
		}
		return null;
	}
}
